package com.example.common.file;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

public class FileCompareUtil {
    public static String calculateMD5(File file) {
        try (FileInputStream fis = new FileInputStream(file)) {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }
            byte[] digest = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5计算失败", e);
        }
    }

    public static boolean areFilesEqual(File file1, File file2) {
        return calculateMD5(file1).equals(calculateMD5(file2));
    }
}